﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Parsowanie;
using Portfel.IS;

namespace Portfel.Web
{
    public static class WebData
    {

        public static void GetData()
        {
            GetAkcje();
            GetObligacje();
        }

        public static void GetAkcje(Action action = null)
        {
            const string uri = "http://www.bankier.pl/inwestowanie/notowania/akcje.html";
            var request = (HttpWebRequest)WebRequest.Create(uri);
            var a = new AsyncCallback(delegate(IAsyncResult ar)
            {
                ReadWebRequestCallbackAkcje(ar);
                if (action != null) action();
            });
            request.BeginGetResponse(a, request);
        }



        public static void GetObligacje(Action action=null)
        {
            const string uri = "http://www.bankier.pl/inwestowanie/notowania/obligacje.html";
            var request = (HttpWebRequest)WebRequest.Create(uri);
            var a = new AsyncCallback(delegate(IAsyncResult ar)
            {
                ReadWebRequestCallbackObligacje(ar);
                if (action != null) action();
            });
            request.BeginGetResponse(a, request);
        }

        private static void ReadWebRequestCallbackAkcje(IAsyncResult callbackResult)
        {
            ReadWebRequestCallback(callbackResult, IsolatedStorageHelper.AkcjeFile, HtmlSecurityParser.GetIndeces);
        }

        private static void ReadWebRequestCallbackObligacje(IAsyncResult callbackResult)
        {
            ReadWebRequestCallback(callbackResult, IsolatedStorageHelper.ObligacjeFile, HtmlSecurityParser.GetObligacje);
        }

        private static void ReadWebRequestCallback(IAsyncResult callbackResult, string file,Func<string,List<SecurityIndice>> parser)
        {
            var myRequest = (HttpWebRequest)callbackResult.AsyncState;
            var myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            using (var httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                var data = parser(results);
                IsolatedStorageHelper.WriteToXml(data, file);
            }
            myResponse.Close();
        }

    }
}
